﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IWshRuntimeLibrary;
using Microsoft.Win32;

namespace Tnelab.Setup
{
    public static class SetupHelper
    {
        /// <summary>
        /// 创建程序快捷键
        /// </summary>
        /// <param name="targetPath">程序运行地址</param>
        /// <param name="shortcutName">快捷键名称</param>
        /// <param name="description">说明</param>
        /// <param name="iconLocation">快捷键图标</param>
        public static void CreateShortcutOnDesktop(string targetPath, string shortcutName, string description, string iconLocation)
        {
            //添加引用 (com->Windows Script Host Object Model)，using IWshRuntimeLibrary;            
            String shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), shortcutName + ".lnk");
            if (!System.IO.File.Exists(shortcutPath))
            {
                IWshShell shell = new WshShell();
                // 确定是否已经创建的快捷键被改名了                
                foreach (var item in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "*.lnk"))
                {
                    WshShortcut tempShortcut = (WshShortcut)shell.CreateShortcut(item);
                    if (tempShortcut.TargetPath == targetPath)
                    {
                        return;
                    }
                }
                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象
                shortcut.TargetPath = targetPath;//指定目标路径
                shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
                shortcut.WindowStyle = 1;//设置运行方式，默认为常规窗口
                shortcut.Description = description;//设置备注
                shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
                shortcut.Save();//保存快捷方式
            }
        }

        /// <summary>
        /// 创建程序菜单快捷方式
        /// </summary>
        /// <param name="targetPath">可执行文件路径</param>
        /// <param name="description">快捷方式名称</param>
        /// <param name="menuName">程序菜单中子菜单名称，为空则不创建子菜单</param>
        /// <param name="iconLocation">快捷方式图标路径</param>
        /// <param name="workingDirectory">工作路径</param>
        /// <returns></returns>
        public static void CreateProgramsShortcut(string softName,string targetPath, string shortcutName, string description, string iconLocation,bool toCreateProgramsFolder = false)
        {
            String softPath = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
            if (toCreateProgramsFolder)
            {
                softPath = Path.Combine(softPath, softName);
            }
            String shortcutPath = Path.Combine(softPath, shortcutName + ".lnk") ;
            if (!System.IO.File.Exists(shortcutPath))
            {
                IWshShell shell = new WshShell();
                // 确定是否已经创建的快捷键被改名了                
                foreach (var item in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "*.lnk"))
                {
                    WshShortcut tempShortcut = (WshShortcut)shell.CreateShortcut(item);
                    if (tempShortcut.TargetPath == targetPath)
                    {
                        return;
                    }
                }
                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象
                shortcut.TargetPath = targetPath;//指定目标路径
                shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
                shortcut.WindowStyle = 1;//设置运行方式，默认为常规窗口
                shortcut.Description = description;//设置备注
                shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
                shortcut.Save();//保存快捷方式
            }
        }



        /// <summary>  
        /// 修改程序在注册表中的键值  开机自启
        /// 注册表地址：HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
        /// </summary>  
        /// <param name="isAuto">true:开机启动,false:不开机自启</param> 
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416:验证平台兼容性", Justification = "<挂起>")]
        public static void SetAutoStart(string softName, bool isAuto, string path)
        {
            try
            {
                if (isAuto == true)
                {
                    RegistryKey R_local = Registry.CurrentUser;
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.SetValue(softName, path);
                    R_run.Close();
                    R_local.Close();
                }
                else
                {
                    RegistryKey R_local = Registry.CurrentUser;
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.DeleteValue(softName, false);
                    R_run.Close();
                    R_local.Close();
                }
            }
            catch (Exception)
            {
            }
        }


        /// <summary>
        /// 将程序添加到控制面板的卸载内
        /// </summary>
        /// <param name="softName"></param>
        /// <param name="installInfo"></param>
        /// <param name="softwareInfo"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416:验证平台兼容性", Justification = "<挂起>")]
        public static void SetUnInstall(string softName, SoftwareInstallInfo installInfo, SoftwareInfo softwareInfo)
        {
            RegistryKey soft = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + softName);
            soft.SetValue("DisplayIcon", softwareInfo.DisplayIcon);
            soft.SetValue("DisplayName", softwareInfo.DisplayName);
            soft.SetValue("DisplayVersion", softwareInfo.DisplayVersion);
            soft.SetValue("EstimatedSize", softwareInfo.EstimatedSize);//大小
            soft.SetValue("URLInfoAbout", softwareInfo.URLInfoAbout);//支持链接
            soft.SetValue("InstallLocation", softwareInfo.InstallLocation);//安装目录
            soft.SetValue("Publisher", softwareInfo.Publisher);//发布者
            soft.SetValue("UninstallString", softwareInfo.UninstallString);//卸载程序路径
            soft.Close();
            soft = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\" + softName);
            soft.SetValue("InstallPath", installInfo.InstallPath);
            soft.SetValue("Version", installInfo.Version);
            soft.Close();
        }


        /// <summary>
        /// 清除安装注册表信息
        /// </summary>
        /// <param name="softName"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416:验证平台兼容性", Justification = "<挂起>")]
        public static void ClearInstallInfo(string softName)
        {
            SetAutoStart(softName, false, null);
            Registry.LocalMachine.DeleteSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + softName);
            Registry.LocalMachine.DeleteSubKey(@"SOFTWARE\" + softName);
        }
    }
}
